//
//  ViewController.m
//  ContactsCoreData
//
//  Created by dllo on 15/11/20.
//  Copyright © 2015年 张树林. All rights reserved.
//

#import "SLViewController.h"
#import "SLCoreDataHandler.h"
#import "SLContactCell.h"
#import "SLDetailViewController.h"



@interface SLViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *modelArray;

@end

@implementation SLViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)createData
{
    self.modelArray = [SLCoreDataHandler selectAll];
    
    NSLog(@"%@", self.modelArray);
    
    [self.tableView reloadData];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSLog(@"segue: %@", segue.identifier);
    if ([segue.identifier isEqualToString:@"detail"]) {
       
        SLDetailViewController *detailVC = segue.destinationViewController;
        SLContactCell *cell = (SLContactCell *)sender;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        
        detailVC.model = self.modelArray[indexPath.row];
        
    }
}


#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"%ld", self.modelArray.count);
    return self.modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"contact";
    
    SLContactCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    
    if (! cell) {
        cell = [[SLContactCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
    }
    
    cell.model = self.modelArray[indexPath.row];
    
    return cell;
}


@end
